<template>
	<view class="flex-col page">
		<view class="flex-col">
			<view class="flex-col">
				<view class="flex-row items-center group">
					<view class="flex-row items-center" @click="toLocate">
						<image class="shrink-0 image_6" src="/static/map.png" />
						<text class="text_3">{{address}}</text>
						<image class="shrink-0 image_8" src="/static/more.png" />
					</view>
					<view class="flex-row items-center flex-auto section_3 space-x-13" @click="toSearch">
						<image class="image_7" src="/static/search.png" />
						<text class="font_3 text_4">搜索...</text>
					</view>
				</view>
				<view class="swiper">
					<swiper :autoplay="true" :interval="4000" :duration="500" @change="onChange">
						<swiper-item v-for="(item,index) in indexList.swiperUrl" :key="index">
							<view class="swiper-item" @click="toTarget(item)">
								<image :src="item.abs_url+ '?t=' + Date.now()" alt="" class="swiper-item-image" mode="aspectFill"></image>
							</view>
						</swiper-item>
					</swiper>
					<view class="swiper_dots">
						<view v-for="(item,index) in indexList.swiperUrl" :key="index">
							<view class="dot" :class="(index == currentSwiper ? 'active' : '')"></view>
						</view>
					</view>
				</view>
				<view class="grid">
					<view class="flex-col items-center grid-item space-y-20" v-for="(item,index) in indexList.navs"
						:key="index" @click="toTarget(item)">
						<image class="image_10" :src="item.icon_path" />
						<text class="font_3">{{item.name}}</text>
					</view>
				</view>
				<text class="self-start font_2 text_5">附近商家</text>
				<view class="flex-row group_2 view space-x-28">
					<view class="flex-col justify-start items-center text-wrapper" @click="toSort(0)"
						:style="indexList.sort==''?'color:#54BC6E;':''">
						<text class="font_4">综合排序</text>
					</view>
					<view class="flex-col justify-start items-center text-wrapper" @click="toSort(1)"
						:style="indexList.sort=='sale'?'color:#54BC6E;':''">
						<text class="font_4">销量最高</text>
					</view>
					<view class="flex-col justify-start items-center text-wrapper" @click="toSort(2)"
						:style="indexList.sort=='nearby'?'color:#54BC6E;':''">
						<text class="font_4">距离最近</text>
					</view>
					<view class="flex-col justify-start items-center text-wrapper" @click="toSort(3)"
						:style="indexList.sort=='score'?'color:#54BC6E;':''">
						<text class="font_4">评分最高</text>
					</view>
				</view>
				<view class="flex-col group_2 group_3 space-y-20">
					<view class="flex-row list-item" v-for="(item, index) in indexList.list" :key="index"
						@click="toBuy(item.shop_id)">
						<view class="flex-row relative">
							<image class="shrink-0 self-center image_11" :src="item.cover"
								loading="eager" />
							<image class="shrink-0 self-center image_11" v-if="item.is_on!=1"
								style="position: absolute;top: 0;left: 0;" src="/static/trade.png" />
						</view>
						<view class="flex-col flex-auto self-center group_4 space-y-23">
							<view class="flex-row items-center space-x-8">
								<text class="font_5">{{item.shop_name}}</text>
								<image class="image_12" v-if="item.is_license==1" src="/static/success.png" />
							</view>
							<view class="flex-row">
								<text class="font_6 text_6">{{item.score}}分</text>
								<view class="shrink-0 section_4 view_2"></view>
								<text class="font_7 text_7">人均￥{{item.avg_amounts}}</text>
								<view class="shrink-0 section_4 view_3"></view>
								<text class="font_7 text_8">销售{{item.sales}}</text>
							</view>
							<view class="flex-row justify-start items-center self-start" style="flex-wrap: wrap;">
								<view class="text-wrapper_2" v-for="(item1,index1) in item.tags" :key="index1">
									<text class="font_8">{{item1}}</text>
								</view>
								
							</view>
						</view>
						<text class="self-start font_9 text_9 text_10">距我{{item.distance}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onLaunch,
		onShow,
		onReachBottom,
		onPullDownRefresh,
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		onMounted,
		ref,
		reactive,
		getCurrentInstance,
		nextTick
	} from "vue"
	import amapFile from '../../utils/amap-uni.130.js'
	const myAmapFun = new amapFile.AMapWX({
		key: '3a26f7397fc12384590ae0a8ab25443b'
	});
	const {
		proxy
	} = getCurrentInstance()
	onMounted(() => {
		console.log("onMounted");
	})
	onLaunch(() => {
		console.log("onLaunch");
		console.log("12345");
		uni.reLaunch({
			url: '/pages/index/index' // 替换为当前页面的路径
		})
	})
	onLoad((option) => {
		console.log("onload");
		showLoad.value = true
		// toSign()
		// getLocat()
		// getlist()
		getLocat()
		getDate()

		// let  isFirstLoad = !uni.getStorageSync('hasIndex')
		// console.log(isFirstLoad,"isFirstLoad");
		// if (isFirstLoad) {
		// 	console.log("12345");
		// 	uni.setStorageSync('hasIndex', true)

		// }
		// nextTick(()=>{
		// 	console.log("location======");
		// 	location.reload()
		// })
		// getConf()
		// uni.setStorageSync('member_id',"1")
		uni.$on('mapList1', function(res) {
			console.log(res, "mapList1");
			address.value = res.address
			indexList.value.list.length = 0
			uni.setStorageSync('address', res)
			uni.setStorageSync('latitude', res.lat)
			uni.setStorageSync('longitude', res.lng)
			if (res.city_code) {
				city_code.value = res.city_code
			}
			longitude.value = res.lng
			latitude.value = res.lat
			let locat = [longitude.value, latitude.value]
			let location = locat.join(',')
			if (res.lng != '') {
				getRegeo(location)
			} else {
				getlist()
			}
		})
		if (option.invite_id) {
			uni.setStorageSync('invite_id', option.invite_id)
		}
	})
	onShareAppMessage(() => {
		return {
			title: '', //分享的名称

		}
	})
	onShareTimeline(() => {
		return {
			title: '', //分享的名称
		}
	})
	onReachBottom(() => {
		console.log("上拉");
		p.value++
		getlist()
	})

	onPullDownRefresh(() => {
		// getDate()
		console.log("下拉");
		indexList.list.length = 0
		tags.value.length = 0
		sort.value = ''
		// p.value = 1
		// getlist()
		uni.stopPullDownRefresh()
	})
	onShow(() => {
		indexList.sort = false
	})
	let globalData = ref(uni.getStorageSync('globalData') || '')

	let address = ref('###')
	let city_code = ref('')
	// let city_name = ref('')
	// let district_name = ref('')
	// let province_name = ref('')

	let currentSwiper = ref(0)

	const onChange = (e) => {
		// console.log(e);
		currentSwiper.value = e.detail.current
	}
	// let tags = ref([])
	let sort = ref('')
	let p = ref(1)
	let showLoad = ref(false)
	let indexList = ref({
		content: {
			alert: []
		},
		swiperUrl: [],
		navs: [],
		tags: ['热销', '附近'],
		tag: 0,
		list: [],
		sort: '',
		show: false,
		newgoods: [],
		secgoods: [],
		timeData: {}
	})
	let longitude = ref('')
	let latitude = ref('')
	const toSign = () => {
		proxy.$req.requestPOST(proxy.$api.IndexInfo.getSign, {
			url: window.location.origin + window.location.pathname
		}).then(res1 => {
			console.log(res1);
			if (res1.flag == 'success') {
				let config = {
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: 'wxc4f5144cd4a7f83b', // 必填，公众号的唯一标识
					timestamp: res1.data.timestamp, // 必填，生成签名的时间戳
					nonceStr: res1.data.noncestr, // 必填，生成签名的随机串
					signature: res1.data.sign, // 必填，签名
					jsApiList: ['getLocation'] // 必填，需要使用的JS接口列表
				}
				console.log(config, 'config');
				proxy.$wx.config(config)
				proxy.$wx.error(function(res) {
					// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					console.log("config信息验证失败");
					console.log(res);
					uni.showModal({
						title: JSON.stringify(res.mesage)
					})
				})
				proxy.$wx.ready(res2 => {
					console.log(res2, 'res2');
					getLocat()
				})
			}
		})
	}
	
	const getLocat = () => {
		console.log('getLocat');
		uni.getLocation({
			// type: 'gcj02',
			success(res) {
				console.log(res);
				longitude.value = res.longitude //117.180424 116.480225
				latitude.value = res.latitude //39.141646 39.947278
				uni.setStorageSync('latitude', latitude.value)
				uni.setStorageSync('longitude', longitude.value)
				let locat = [longitude.value, latitude.value]
				let location = locat.join(',')
				getRegeo(location)
				// myAmapFun.getRegeo({
				// 	location: location,
				// 	success: function(data) {
				// 		console.log(data, "回调成功")
				// 		// address.value = data[0].name
				// 		city_code.value = data[0].regeocodeData.addressComponent.citycode
				// 		uni.setStorageSync('citycode', city_code.value)
				// 		// console.log(city_code.value);
				// 		if (data[0].regeocodeData.addressComponent.city && data[0]
				// 			.regeocodeData.addressComponent.city.length > 0) {
				// 			address.value = data[0].regeocodeData.addressComponent.city
				// 		} else {
				// 			address.value = data[0].regeocodeData.addressComponent.province
				// 		}
				// 		getlist()
				// 		// province_name.value = data[0].regeocodeData.addressComponent.province
				// 		// district_name.value = data[0].regeocodeData.addressComponent.district
				// 	},
				// 	fail: function(info) {
				// 		console.log(info, "回调失败")
				// 	}
				// })

			},
			fail(res) {
				// console.log(res, "err");
				if (res.errMsg.indexOf('permission') !== -1) {
					console.log('用户拒绝了位置权限');
					// uni.showModal({
					// 	title: '需要位置权限',
					// 	content: '为了提供更好的服务，请允许访问您的位置信息。',
					// 	showCancel: false, // 可以选择是否显示取消按钮
					// 	confirmText: '去设置',
					// 	success: function(res) {
					// 		if (res.confirm) {
					// 			// 引导用户去设置页面开启权限
					// 			if (uni.getSystemInfoSync().platform === 'android') {
					// 				plus.android.importClass(plus.android.Intent); // 导入Intent类
					// 				var mainIntent = new Intent(
					// 					'android.settings.APPLICATION_DETAILS_SETTINGS'
					// 					); // 获取应用详情页面Intent对象
					// 				mainIntent.addCategory(Intent
					// 				.CATEGORY_DEFAULT); // 设置Intent的类别为默认类别
					// 				mainIntent.setData(Uri.parse('package:' + plus.android
					// 					.runtimeMainActivity().getPackageName()
					// 					)); // 设置Intent的数据为当前应用的包名（此处用的是原生方式，可能需要适配）
					// 				plus.android.runtimeMainActivity().startActivity(
					// 				mainIntent); // 启动Intent对象对应的Activity组件（原生方式）
					// 			} else if (uni.getSystemInfoSync().platform === 'ios') {
					// 				plus.ios.importClass(UIApplication); // 导入UIApplication类（原生方式）
					// 				var application = plus.ios.UIApplication
					// 				.sharedApplication(); // 获取共享的UIApplication实例（原生方式）
					// 				application.openURL(plus.ios.NSURL.URLWithString(
					// 					'App-Prefs:root=LOCATION_SERVICES')); // 打开系统设置页面（原生方式）
					// 			} else {
					// 				console.log(
					// 				'Unsupported platform'); // 非Android或iOS平台，可能需要其他处理或提示用户手动打开设置页面。
					// 			}
					// 		}
					// 	}
					// });
				} else {
					console.log('获取位置失败', res);
				}
			}
		})
	}
	const getRegeo = (location) => {
		myAmapFun.getRegeo({
			location: location,
			success: function(data) {
				console.log(data, "回调成功")
				// address.value = data[0].name
				city_code.value = data[0].regeocodeData.addressComponent.citycode
				uni.setStorageSync('citycode', city_code.value)
				// console.log(city_code.value);
				if (data[0].regeocodeData.addressComponent.city && data[0]
					.regeocodeData.addressComponent.city.length > 0) {
					address.value = data[0].regeocodeData.addressComponent.city
				} else {
					address.value = data[0].regeocodeData.addressComponent.province
				}
				getlist()
				// province_name.value = data[0].regeocodeData.addressComponent.province
				// district_name.value = data[0].regeocodeData.addressComponent.district
			},
			fail: function(info) {
				console.log(info, "回调失败")
			}
		})
	}

	const getDate = () => {
		proxy.$req.requestGET(proxy.$api.IndexInfo.index).then(res => {
			// indexList.swiperUrl.push(...res.data.banners)
			indexList.value.swiperUrl = res.data.banners
			indexList.value.navs = res.data.navs
			// indexList.value.tags = res.data.tags
			// console.log(indexList.value);
		})
	}
	const getlist = () => {
		console.log(city_code.value);
		proxy.$req.requestPOST(proxy.$api.ShopInfo.getList, {
			lng: longitude.value,
			lat: latitude.value,
			sort: indexList.value.sort,
			citycode: city_code.value,
			p: p.value
		}).then(res => {
			console.log(res);
			showLoad.value = false
			indexList.value.list = [...indexList.value.list, ...res.data.list]
			console.log(indexList.value.list);
			nextTick(() => {
				console.log("1234");
				proxy.$forceUpdate()
			})
		})
	}
	const onChangeDown = (e) => {
		indexList.value.timeData = e
	}
	const toTags = (v) => {
		indexList.value.tag = v
		indexList.value.list.length = 0
		// p.value = 1
		// if (tags.value.indexOf(v.name) == -1) {
		// 	tags.value.push(v.name)
		// } else {
		// 	tags.value.splice(tags.value.indexOf(v.name), 1)
		// }
		getlist()
	}
	const toSort = (num) => {
		if (num == 0) {
			indexList.value.sort = ''
		} else if (num == 1) {
			indexList.value.sort = 'sale'
		} else if (num == 2) {
			indexList.value.sort = 'nearby'
		} else if (num == 3) {
			indexList.value.sort = 'score'
		}
		p.value = 1
		indexList.value.list.length = 0
		getlist()
	}
	const toTarget = (v) => {
		console.log(v);
		switch (v.target_rule) {
			case '1':
				//网址
				uni.navigateTo({
					url: "/pages/webHttp/webHttp?url=" + JSON.stringify(v.param)
				})
				break;
			case '2':
				//商家列表(标签) -- 标签ID 　
				uni.navigateTo({
					url: "/pages/business/business?tag_id=" + v.param
				})
				break;
			case '3':
				//商家列表(关键词) -- 关键词
				uni.navigateTo({
					url: "/pages/business/business?keywords=" + v.param
				})
				break;
			case '4':
				//商家详情--商家ID
				uni.navigateTo({
					url: "/pages/businessDetail/businessDetail?shop_id=" + v.param
				})
				break;
			case '0':
				//商家详情--商家ID
				uni.navigateTo({
					url: "/pages/business/business"
				})
				break;
			default:
				break;
		}
	}
	const toBuy = (shop_id) => {
		uni.navigateTo({
			url: '/pages/businessDetail/businessDetail?type=1&shop_id=' + shop_id
		})
	}
	const toLocate = () => {
		uni.navigateTo({
			url: '/pages/location/location'
		})
	}
	const toSearch = () => {
		uni.navigateTo({
			url: '/pages/search/search'
		})
	}
	const toBusiness = (shop_id, v) => {
		if (v.is_on == 0) {
			uni.showToast({
				title: '该商家未营业',
				icon: 'none'
			})
			return
		}
		uni.navigateTo({
			url: '/pages/business/business?shop_id=' + shop_id
		})
	}
</script>

<style scoped lang="scss">
	.page {
		background-color: #f8f8f8;
		width: 100%;
		overflow-y: auto;
		overflow-x: hidden;
		height: 100vh;

		.section {
			padding: 34rpx 28rpx 29rpx 63rpx;
			background-color: #ffffff00;

			.font_1 {
				font-size: 28rpx;
				font-family: PingFangSC;
				letter-spacing: 1.4rpx;
				color: #ffffff;
			}

			.text {
				line-height: 21rpx;
			}

			.text_2 {
				line-height: 15rpx;
			}

			.pos {
				position: absolute;
				left: 20rpx;
				bottom: 3rpx;
			}
		}

		.section_2 {
			padding: 27rpx 12rpx;
			background-color: #ffffff00;

			.image-wrapper {
				width: 73rpx;

				.image_4 {
					width: 24rpx;
					height: 24rpx;
				}

				.image_5 {
					width: 34rpx;
					height: 6rpx;
				}
			}

			.pos_2 {
				position: absolute;
				left: 12rpx;
				top: 50%;
				transform: translateY(-50%);
			}

			.pos_3 {
				position: absolute;
				right: 19rpx;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.group {
			padding: 27rpx 30rpx 24rpx 33rpx;

			.image_6 {
				width: 24rpx;
				height: 28rpx;
			}

			.text_3 {
				margin-left: 9rpx;
				color: #111;
				font-size: 28rpx;
				font-family: PingFangSC;
				line-height: 27rpx;
			}

			.image_8 {
				margin-left: 7rpx;
				border-radius: 2rpx;
				width: 12rpx;
				height: 8rpx;
			}

			.section_3 {
				margin-left: 26rpx;
				padding: 20rpx 30rpx;
				background-color: #ffffff;
				border-radius: 34rpx;
				height: 68rpx;

				.image_7 {
					width: 28rpx;
					height: 28rpx;
				}

				.text_4 {
					color: #999999;
				}
			}

			.space-x-13 {

				&>view:not(:first-child),
				&>text:not(:first-child),
				&>image:not(:first-child) {
					margin-left: 13rpx;
				}
			}
		}

		.swiper {
			width: 93%;
			height: 284rpx;
			margin: 0 auto;

			// margin-top: -190rpx;
			/* position: absolute;
			top: 20rpx; */
			/* margin-left: 5%; */
			.swiper-item {
				width: 100%;
				height: 284rpx;

				&-image {
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
				}
			}

			.swiper_dots {
				width: 100%;
				height: 36rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: row;
				margin-top: -53rpx;
				position: relative;

				.dot {
					width: 10rpx;
					height: 10rpx;
					border-radius: 7.5rpx;
					margin-right: 15rpx;
					background-color: rgba(255, 60, 46, .3);
				}

				.active {
					// width: 18rpx;
					background-color: rgba(255, 60, 46, 1);
				}
			}
		}

		.grid {
			margin-top: 22rpx;
			// height: 356rpx;
			display: grid;
			grid-template-columns: repeat(4, 1fr);

			.grid-item {
				padding: 18rpx 0;

				.image_10 {
					width: 96rpx;
					height: 96rpx;
				}
			}
		}

		.font_3 {
			font-size: 26rpx;
			font-family: PingFangHeiTC;
			line-height: 25rpx;
			color: #666666;
		}

		.font_2 {
			font-size: 36rpx;
			font-family: PingFangSC;
			line-height: 34rpx;
			color: #333333;
		}

		.text_5 {
			margin-left: 32rpx;
			margin-top: 36rpx;
		}

		.group_2 {
			padding: 0 30rpx;

			.text-wrapper {
				flex: 1 1 152rpx;
				padding: 16rpx 0;
				background-color: #efefef;
				border-radius: 10rpx;
				height: 54rpx;
				font-size: 22rpx;
				font-family: PingFangHeiTC;
				line-height: 21rpx;
				color: #666666;

				.font_4 {}
			}

			.list-item {
				padding: 32rpx 28rpx;
				background-color: #ffffff;
				border-radius: 20rpx;

				.image_11 {
					border-radius: 20rpx;
					width: 196rpx;
					height: 148rpx;
				}

				.group_4 {
					margin-left: 20rpx;

					.font_6 {
						font-size: 24rpx;
						font-family: PingFangHeiTC;
						line-height: 23rpx;
						color: #f52c2c;
					}

					.text_6 {
						line-height: 22rpx;
					}

					.section_4 {
						background-color: #c1c1c1;
						border-radius: 0.5rpx;
						width: 1rpx;
						height: 20rpx;
					}

					.view_2 {
						margin-left: 9rpx;
					}

					.text_7 {
						margin-left: 11rpx;
					}

					.view_3 {
						margin-left: 11rpx;
					}

					.text_8 {
						margin-left: 16rpx;
					}

					.text-wrapper_2 {
						padding: 8rpx;
						background-color: #eff5f0;
						border-radius: 6rpx;
						margin-right: 10rpx;
						margin-bottom: 10rpx;
						// width: 80rpx;
						
						.font_8 {
							font-size: 22rpx;
							font-family: PingFangHeiTC;
							line-height: 21rpx;
							color: #54bc6e;
						}
					}
				}

				.space-y-23 {

					&>view:not(:first-child),
					&>text:not(:first-child),
					&>image:not(:first-child) {
						margin-top: 23rpx;
					}
				}

				.font_9 {
					font-size: 24rpx;
					font-family: PingFang SC;
					line-height: 23rpx;
					color: #aeaeae;
				}

				.text_9 {
					margin-left: 6rpx;
					margin-top: 114rpx;
					line-height: 22rpx;
				}

				.text_10 {
					margin-top: 115rpx;
				}
			}
		}

		.view {
			margin-top: 34rpx;
		}

		.space-x-28 {

			&>view:not(:first-child),
			&>text:not(:first-child),
			&>image:not(:first-child) {
				margin-left: 28rpx;
			}
		}

		.group_3 {
			margin-top: 29rpx;
		}

		.space-y-20 {

			&>view:not(:first-child),
			&>text:not(:first-child),
			&>image:not(:first-child) {
				margin-top: 20rpx;
			}
		}

		.space-x-8 {

			&>view:not(:first-child),
			&>text:not(:first-child),
			&>image:not(:first-child) {
				margin-left: 8rpx;
			}

			.image {
				width: 36rpx;
				height: 24rpx;
			}

			.image_2 {
				width: 32rpx;
				height: 22rpx;
			}

			.image_3 {
				width: 50rpx;
				height: 24rpx;
			}

			.font_5 {
				font-size: 32rpx;
				font-family: PingFangSC;
				line-height: 31rpx;
				color: #333333;
			}

			.image_12 {
				width: 22rpx;
				height: 25rpx;
			}
		}

		.equal-division {
			margin-top: 42rpx;

			.section_7 {
				flex: 1 1 250rpx;

				.image_13 {
					width: 32rpx;
					height: 32rpx;
				}

				.text_12 {
					color: #54bc6e;
				}

				.font_10 {
					font-size: 24rpx;
					font-family: PingFangHeiTC;
					line-height: 23rpx;
					color: #4ec200;
				}
			}

			.equal-division-item {
				padding: 20rpx 0 12rpx;
				background-color: #ffffff;
				height: 100rpx;
			}

			.space-y-15 {

				&>view:not(:first-child),
				&>text:not(:first-child),
				&>image:not(:first-child) {
					margin-top: 15rpx;
				}
			}
		}

		.section_6 {
			background-color: #ffffff;
			border-top: solid 2rpx #f6f6f6;
		}

		.font_7 {
			font-size: 24rpx;
			font-family: PingFangHeiTC;
			line-height: 23rpx;
			color: #585858;
		}
	}
</style>